package com.czkevin.cif;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.PluginCommand;
import org.bukkit.command.TabExecutor;

import java.util.*;

public abstract class CIFCommand implements TabExecutor, CIFSubCommand {

    private final Map<String, CIFSubCommand> commands = new HashMap<>();
    private final List<String> entries = new LinkedList<>();

    protected void registerCommand(CIFSubCommand executor) {
        if(executor.getCommandName() == null) throw new IllegalArgumentException("Invalid name! ");
        String name = executor.getCommandName().toLowerCase();
        if(commands.containsKey(name)) throw new IllegalArgumentException("Already registered! ");
        commands.put(name, executor);
        entries.add(name);
    }

    @Override
    public void execute(CommandSender sender, String[] args) {
        sendHelp(sender);
    }

    @Override
    public final boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        if(args.length == 0) {
            execute(sender, args);
            return true;
        }
        String name = args[0].toLowerCase();
        if(!commands.containsKey(name)) return true;
        CIFSubCommand c = commands.get(name);
        c.execute(sender, Arrays.copyOfRange(args, 1, args.length));
        return true;
    }

    @Override
    public final String getHelpParameters() {
        return null;
    }

    public final void sendHelp(CommandSender sender) {
        if(getHelpText() != null) {
            sender.sendMessage("\u00a76" + getHelpText());
        }
        commands.forEach((key, value) -> sender.sendMessage(
            String.format("\u00a7e/%s \u00a7a%s \u00a7d%s \u00a7a: \u00a7b%s", getCommandName(), key, value.getHelpParameters(), value.getHelpText())
        ));
    }

    @Override
    public List<String> tabComplete(String[] args) {
        return entries;
    }

    @Override
    public final List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
        if(args.length <= 1) return entries;
        String name = args[0].toLowerCase();
        if(!commands.containsKey(name)) return Collections.emptyList();
        CIFSubCommand c = commands.get(name);
        List<String> l = c.tabComplete(Arrays.copyOfRange(args, 1, args.length));
        if(l == null) return Collections.emptyList();
        return l;
    }

    public final void register(PluginCommand pluginCommand) {
        pluginCommand.setExecutor(this);
        pluginCommand.setTabCompleter(this);
    }
}
